﻿package net.wangit.adm.variables;

import net.wangit.Element;
import net.wangit.MapList;
import net.wangit.Unit;
import net.wangit.context.ActionContext;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.DBFactory;
import net.wangit.support.UnitInterceptor;
import net.wangit.util.Checker;
import net.wangit.view.tree.TreeUtil;

public class VariableUI implements UnitInterceptor {

	private static final String SQL_PARENT = "select vid as value ,vname as name,parentid,o from AVARIABLES where vid!=? order by o";
	private static final String SQL_PARENT_ADD = "select vid as value ,vname as name,o from AVARIABLES order by o";

	public VariableUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		MapList data = unit.getData();
		if (!Checker.isEmpty(data)
				&& Checker.isEmpty(data.getRow(0).get("parentid"))) {
			unit.removeElement("parentid");
		} else {
			String unitShowMode = unit.getShowMode();
			DB db = DBFactory.getDB();
			String id = Checker.isEmpty(data) ? "" : data.getRow(0).get("vid");
			MapList list;
			if ("a".equals(unitShowMode))
				list = db.query(VariableUI.SQL_PARENT_ADD);
			else
				list = TreeUtil.filterParentId(db, VariableUI.SQL_PARENT, id,
						"parentid", 2);
			Element element = unit.getElement("parentid");
			element.setObject(list);
			if ("a".equals(unitShowMode))
				element.setDefaultValue(ac.getRequestParameter("parentid"));
		}
		return unit.write(ac);
	}
}
